<?php
namespace zzcms\primary\controller;


class Search extends Base
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 文章搜索
     * 搜索结果排序要求
     * 帮助中心-TOP问答-通知公告
     */
    public function product()
    {
        $page = isset($this->info['page']) ? max(intval($this->info['page']), 1) : 1;
        $pagesize = isset($this->info['pagesize']) ? intval($this->info['pagesize']) : 10;
        $keyword = isset($this->info['keyword']) ? $this->info['keyword'] : '';
        if (empty($keyword)) {
            $this->array2json(['code' => 1, 'msg' => '搜索词不能为空']);
        }
        //解析传过来的参数值
        $keyword = urldecode($keyword);
        $keyword = str_replace('.', '', $keyword);
        $keyword = str_replace('、', '', $keyword);

        // 获取搜索结果的匹配总数估算值
        $pagesize = 20;
        $limit = max(($page - 1) * $pagesize, 0);

        //排序顺序，标题权重-内容权重（帮助中心-TOP问答-通知公告）
        $article_lists = $news_lists = [];

        //引入迅搜,搜索入热词需要用到
        include SITE_PATH . '../extend/xunsearch/lib/XS.php';
        //搜索POS产品

        $xs = new \XS('product');
        $search = $xs->search;
        $products = $search->addDb('product')->addWeight('title', $keyword)->setQuery($keyword)->setLimit($pagesize, $limit)->search();
        $product_ids = [];
        foreach ($products as $k => $item) {
            $product_ids = $item['id'];
        }
        $where = [];
        $where[] = ['id', 'in', $product_ids];
        $product_lists = (new \zzcms\admin\model\Product())->getList(['where' => $where, 'limit' => 'all']);
        if ($product_lists) {
            $brands = getCache('brand', '', ['where' => ['status' => 1], 'order' => 'listorder desc,id desc']);
            //POS机类型
            $product_modules = config('zzcms.product_module');
            //POS机网络
            $product_networks = config('zzcms.product_network');
            //POS机收款方式
            $product_payments = config('zzcms.product_payment');
            //POS机颜色
            $product_colors = config('zzcms.product_color');
            //POS机特色功能
            $product_functions = config('zzcms.product_function');
            foreach ($product_lists as $k => $item) {
                $item['product_module'] = $product_modules[$item['module']];
                $item['product_network'] = str_replace(array_keys($product_networks), $product_networks, $item['network']);
                $item['product_payment'] = str_replace(array_keys($product_payments), $product_payments, $item['payment']);
                $item['product_color'] = str_replace(array_keys($product_colors), $product_colors, $item['pos_color']);
                $item['product_function'] = str_replace(array_keys($product_functions), $product_functions, $item['function']);
                $brand_info = isset($brands[$item['brand_id']]) ? $brands[$item['brand_id']] : [];
                if (empty($brand_info)) {
                    $item['brand_name'] = '';
                    $item['brand_image'] = '';
                } else {
                    $item['brand_name'] = $brand_info['name'];
                    $item['brand_image'] = false === strpos($brand_info['thumb'], 'http') ? 'http://res.xuexiba.net/' . $brand_info['thumb'] : $brand_info['thumb'] . '?x-oss-process=image/resize,m_fill,h_50,w_50';
                }
                $images = empty($item['thumb']) ? [] : explode(',', $item['thumb']);
                if ($images) {
                    foreach ($images as $kk => $image_thumb) {
                        $image_thumb = $image_thumb . '?x-oss-process=image/resize,m_lfit,w_110';
                        $images[$kk] = $image_thumb;
                    }
                }
                $item['images'] = $images;
                $item['brand_image'] = '/static/images/dingdan_03.png';
                $item['images'] = !empty($item['thumb']) ? [] : explode(',', $item['thumb']);
                $item['image'] = !empty($item['thumb']) ? '/static/images/dingdan_03.png' : $item['images'][0];
                //图片数量
                $item['image_count'] = count($item['images']);
                //最多显示几张图片
                $item['show_count'] = 3;
                $item['third_img'] = $item['image_count'] > $item['show_count'] ? $item['images'][2] : '';
                $item['hide_count'] = $item['image_count'] > $item['show_count'] ? $item['image_count'] - $item['show_count'] : 0;
                $product_lists[$k] = $item;
            }
        }
        //搜索POS课堂
        $xs = new \XS('article');
        $search = $xs->search;
        $articles = $search->addDb('article')->addWeight('title', $keyword)->setQuery($keyword)->setLimit($pagesize, $limit)->search();
        //分类缓存
        $category_cache = getCache('category');
        //防止重复ID
        $ids = [];
        foreach ($articles as $k => $item) {
            if (in_array($item['id'], $ids)) {
                continue;
            }
            $ids[] = $item['id'];
            $cateinfo = isset($category_cache[$item['cate_id']]) ? $category_cache[$item['cate_id']] : [];
            if (empty($item['thumb'])) {
                $image = '/static/images/dingdan_03.png';
            } else {
                $image = false === strpos($item['thumb'], 'http') ? 'http://res.xuexiba.net/' . $item['thumb'] : $item['thumb'] . '?x-oss-process=image/resize,m_lfit,w_110';
            }
            $data = [
                'id' => $item['id'], // 主键字段，必须指定
                'title' => $item['title'],
                'type' => 'article',
                'cate_id' => $item['cate_id'],
                'image' => $image,
                'catename' => $cateinfo ? $cateinfo['catename'] : '',
                'hits' => $item['hits'],
                'meta_description' => strip_tags(htmlspecialchars_decode($item['meta_description'])),
                'meta_title' => $item['meta_title'],
                'meta_keywords' => $item['meta_keywords'],
                'listorder' => $item['listorder'],
                'create_time' => $item['create_time']
            ];
            $article_lists[] = $data;
        }
        //搜索POS新闻
        $xs = new \XS('news');
        $search = $xs->search;
        $artilces = $search->addDb('news')->addWeight('title', $keyword)->setQuery($keyword)->setLimit($pagesize, $limit)->search();
        //防止重复ID
        $ids = [];
        foreach ($artilces as $k => $item) {
            if (in_array($item['id'], $ids)) {
                continue;
            }
            $ids[] = $item['id'];
            $cateinfo = isset($category_cache[$item['cate_id']]) ? $category_cache[$item['cate_id']] : [];
            if (empty($item['thumb'])) {
                $image = '/static/images/dingdan_03.png';
            } else {
                $image = false === strpos($item['thumb'], 'http') ? 'http://res.xuexiba.net/' . $item['thumb'] : $item['thumb'] . '?x-oss-process=image/resize,m_lfit,w_110';
            }
            $data = [
                'id' => $item['id'], // 主键字段，必须指定
                'title' => $item['title'],
                'type' => 'news',
                'cate_id' => $item['cate_id'],
                'image' => $image,
                'catename' => $cateinfo ? $cateinfo['catename'] : '',
                'hits' => $item['hits'],
                'meta_description' => strip_tags(htmlspecialchars_decode($item['meta_description'])),
                'meta_title' => $item['meta_title'],
                'meta_keywords' => $item['meta_keywords'],
                'listorder' => $item['listorder'],
                'create_time' => $item['create_time']
            ];
            $news_lists[] = $data;
        }
        $count = count($product_lists) + count($article_lists) + count($news_lists);

        $this->array2json(['code' => 0, 'count' => $count, 'prolist' => $product_lists, 'artlist' => $article_lists, 'newslist' => $news_lists]);
    }

    /**
     * 分词
     * @param $title
     * @param null $num
     * @return array|string
     */
    private function getTags($title, $num = null)
    {
        $pscws = new \zzcms\util\pscws\Pscws4();
        $path = SITE_PATH . '../extend/zzcms/util/pscws/';
        $pscws->set_dict($path . 'dict.utf8.xdb');
        $pscws->set_rule($path . 'etc/rules.utf8.ini');
        $pscws->set_ignore(true);
        $pscws->send_text($title);
        $words = $pscws->get_tops($num);
        $pscws->close();
        $tags = [];
        foreach ($words as $val) {
            $tags[] = $val['word'];
        }
        return implode(',', $tags);
    }

}
